  <?php
 defined('_JEXEC') or die('Restricted access');
/**
* @version		$Id:products.php  1 2013-10-12 13:59:21Z  $
* @package		Cashbag
* @subpackage 	Models
* @copyright	Copyright (C) 2013, . All rights reserved.
* @license #
*/
 defined('_JEXEC') or die('Restricted access');
/**
 * CashbagModelProducts 
 * @author 
 */
 
 
class CashbagModelProducts  extends CashbagModel { 

	
	
	protected $_default_filter = 'a.product_params';   

/**
 * Constructor
 */
	
	public function __construct()
	{
		parent::__construct();

	}

	/**
	* Method to build the query
	*
	* @access private
	* @return string query	
	*/
     //********************************************************************************************
        function checkRef(){
            
            $app    = & JFactory::getApplication();
            $bagref = $app->input->get('bag_ref');
            
            $db     = & JFactory::getDbo();
            
            $query  = "SELECT cb.id, cb.vm_user_id, vu.title AS titre, vu.last_name AS nom, vu.first_name AS prenom,
                                vu.address_1 AS adresse, vu.city AS ville, vu.zip AS code_postale
                        FROM #__virtuemart_userinfos AS vu,#__vm_cashbag AS cb
                        WHERE  cb.ref_interne='".$bagref."' AND cb.vm_user_id=vu.virtuemart_user_id AND cb.published = 1";
            $db->setQuery($query);
           // return $query;
            $res    = $db->loadAssocList();
            
            if(count($res)<=0) return -1;
            
            $bag_id = $res[0]['id'];
           
            if($this->send_reception_mail($bag_id)){
                return $res;
            }
            else {
                $res= new stdClass();
                $res[0]->id = 'Une erreur s\'est produite lors de l\'envoie du mail au client';
                return $res;
            }
        }
        function send_reception_mail($bag_id){//envoie un email au client pour lui dire que son sac a été recçu!
            
             $db		= &JFactory::getDbo();
            
            //$bag_id     = JFactory::getApplication()->input->get('bag_id');
            
            $query  ="SELECT p.product_type, p.product_state, p.product_cash_price,  mf.mf_name, cb.vm_user_id, cb.ref_interne, cb.published, cb.receivedOn "
                    ." FROM #__virtuemart_products AS p"
                    ." JOIN #__virtuemart_product_manufacturers AS m ON p.virtuemart_product_id = m.virtuemart_product_id"
                    ." JOIN #__virtuemart_manufacturers_fr_fr AS mf ON m.virtuemart_manufacturer_id = mf.virtuemart_manufacturer_id"
                    . " JOIN #__vm_cashbag AS cb ON p.cashbag_id = cb.id "
                    . " WHERE p.cashbag_id = $bag_id LIMIT 1";
            
            $db->setQuery($query);
            
           // var_dump($query);die();
            
           $details_bag = $db->loadObjectList();//on retourne le résultat!
           //var_dump($details_bag);die();
           if($details_bag[0]->receivedOn=='0000-00-00 00:00:00' || $details_bag[0]->receivedOn== 'NULL'){//si c'est la première qu'on ouvre le cashbag, alors envoyer un mail
               
                $id_user     = $details_bag[0]->vm_user_id;
            // var_dump($id_user);
               $user =& JFactory::getUser($id_user);
                //$session =& JFactory::getSession();

            $nom = $user->name;
            $mail = $user->email;
            //var_dump($mail);die();
            $db = &JFactory::getDbo();

            $query  = "SELECT first_name FROM #__virtuemart_userinfos WHERE virtuemart_user_id = $id_user";
            $db->setQuery($query);
            $r = $db->loadAssoc();

            $prenom = ucfirst($r['first_name']);

            $content    = file_get_contents(JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'letters'.DS.'reception.html');

            $content = utf8_encode($content);

            $message    = str_replace('{prenom}', $prenom, $content);

            $to      = $mail;
            $subject = 'cashdressing.com a reçu votre CASHBAG';
            $headers = 'From: contact@cahsdressing.com' . "\r\n" .
                        'Reply-To: contact@cahsdressing.com, kmartin@cashdressing.com' . "\r\n" .
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=utf-8\r\n";//ISO-8859-1
            //return JFactory::
            if( mail($to, $subject, $message, $headers)){//si le mail a bien été envo
                
               return $this->changeBagStatus($bag_id);
            }
        }
        return true;
    }
        
        function changeBagStatus($id){
            
             $bag    = new stdClass();
            
             $today  = JFactory::getDate()->format('Y-m-d H:m:s');
            $db     = &JFactory::getDbo();
            $bag->id                        = $id;
            $bag->receivedOn                = $today;
            
            $result = JFactory::getDbo()->updateObject('#__vm_cashbag', $bag, 'id');
            return $result;
            
        }
        function getMarqueFilter(){
            
        $db= JFactory::getDbo();
    	$query= $db->getQuery(true);
    	$query->select('DISTINCT virtuemart_manufacturer_id AS id,mf_name AS marque_produit');
    	$query->from($db->quoteName('#__virtuemart_manufacturers_fr_fr'));
    	$query->where($db->quoteName('mf_name') . ' <>  ""');
    	$query->order('mf_name ASC');
    	
    	// Reset the query using our newly populated query object.
    	$db->setQuery($query);
    	
    	// Load the results as a list of stdClass objects (see later for more options on retrieving data).
    	$marques = $db->loadObjectList();
    	
    	
    	if (count($marques)>1) {// s'il y a plus d'un context, alors alors le filtre sera present!
    		 
    		$options = array();
    		$options[] = JHTML::_('select.option', '','S&eacute;lectionnez');
    		foreach ($marques AS $ct) {
    			$options[] = JHTML::_('select.option', $ct->id, $ct->marque_produit);
    		}
    		 
    		$html	= '<td><label>Sélectionner une marque</label></td>';
    		$html	.= '<td>'.JHTML::_('select.genericlist', $options, 'marque_produit', '', 'value', 'text', '').'</td>';
    		 
        }
        
        return $html;
      }
      
      
      public function list_marque(){
            
            $db		= $this->getDbo();
            $query	= $db->getQuery(true);
            
            $query->select('*');
            $query->from('#__vm_estimations');
            $query->where('1');
            $query->order('marque_produit');
            $db->setQuery($query);
            
            return $db->loadAssocList();//on retourne le résultat!
        }
        
        public function list_price(){
            
            $db = &JFactory::getDbo();
            
            $query  = "SELECT * FROM #__vm_price_ref WHERE 1";
            
            $db->setQuery($query);
           
            return $db->loadAssocList();
        }
       
      
      /*function getmarque(){
          
          return JFactory::getApplication()->input->get('id_marque');
      }*/
        function saveProduct(){
            
            $app    = & JFactory::getApplication()->input;
            $res    = true;
            //$ajax   = json_decode(file_get_contents('php://input'));
            //Produit
            
            $record= new stdClass();
            $record->cashbag_id                 = $app->get('cashbag_id');
            $record->product_couleur            = $app->get('product_color');
            $record->product_matiere            = $app->get('product_matiere');
            $record->product_cash_comment       = str_replace('_',' ',$app->get('comments'));//htmlspecialchars($ajax->comments);//
            $record->product_state              = $app->get('etat_produit');//etat du produit
            $record->product_type               = $app->get('type_produit');
            $record->product_cash_price         = doubleval($app->get('product_price'));//
            $record->product_sku                = $app->get('product_sku');
            $record->created_by                 = JFactory::getUser()->get('id');
            $record->created_on                 = JFactory::getDate()->format('Y-m-d H:m:s');
            
            //var_dump($record);die();
            $res        = $res && JFactory::getDbo()->insertObject("#__virtuemart_products", $record);
            if(!$res) die('1');
            $prod_id    = JFactory::getDbo()->insertid();
           
            //Produit + marques
            $marq_prod  = new stdClass();
            $marq_prod->virtuemart_product_id          = $prod_id;
            $marq_prod->virtuemart_manufacturer_id     = $app->get('marque_produit');
            
            $res    = $res && JFactory::getDbo()->insertObject('#__virtuemart_product_manufacturers', $marq_prod);
            
             if(!$res) die('2');
            //Produit + prix
            $prod_price = new stdClass();
            $prod_price->virtuemart_product_id  = $prod_id;
            $prod_price->product_price          = $app->get('product_price');//juste un exemple
            $prod_price->override               = 0;
            $prod_price->product_override_price = 0.000;
            $prod_price->product_tax_id         = 0;
            $prod_price->product_currency       = 47;
            $prod_price->created_by             = JFactory::getUser()->get('id');
            $prod_price->created_on             = JFactory::getDate()->format('Y-m-d H:m:s');
            
            $res    = $res && JFactory::getDbo()->insertObject('#__virtuemart_product_prices', $prod_price);
             if(!$res) die('3');
            //product description
             
              $prod     = new stdClass();
              
              $prod->virtuemart_product_id  = $prod_id;//the last insert id
              $prod->product_name           = $app->get('product_name');
              $prod->product_desc           = $app->get('product_name');
              $prod->product_s_desc         = $app->get('product_name');
              $prod->metadesc               = $app->get('product_name');
              $prod->metakey                = $app->get('product_name');
              $prod->customtitle            = $app->get('product_name');
              $prod->slug                   = $app->get('product_name');
               
             $res = $res && JFactory::getDbo()->insertObject("#__virtuemart_products_fr_fr", $prod);
             
             //incrementer le nbre de produits
             $id    = $app->get('cashbag_id');
             $db     = &JFactory::getDbo();
            $query  = "SELECT count(*) FROM #__virtuemart_products  WHERE cashbag_id = $id ";
            $db->setQuery($query);
            
            $nb                             = $db->loadResult();
            $cashb                          = new stdClass();
            $cashb->id                      = $id;
            $cashb->number_of_product_cash  = $nb;
            
            $res = $res && JFactory::getDbo()->updateObject('#__vm_cashbag', $cashb, 'id');
            if($res) return $nb;
            else return -1;
              
        }
        
        function endReception(){
            
            $id    = JFactory::getApplication()->input->get('bag_id');
            $today  = JFactory::getDate()->format('Y-m-d H:m:s');
            $db     = &JFactory::getDbo();
            
            //count the number of products
            $query  = "SELECT count(p.*) FROM #__virtuemart_products AS p WHERE p.cashbag_id = $id ";
            $db->setQuery($query);
            $nb     = $db->loadResult();
            
            if($nb==0) return -1;
            
            $bag    = new stdClass();
            
            $bag->id                        = $id;
            $bag->receivedOn                = $today;
            $bag->number_of_product_cash    = $nb;
            
            $result = JFactory::getDbo()->updateObject('#__vm_cashbag', $bag, 'id');
            
            if($result) return 1;
            
            return 0;
            
        }
        
        
        
        public function bagdetails(){
            
          $db		= &JFactory::getDbo();
            
            $bag_id     = JFactory::getApplication()->input->get('bag_id');
            
            $query  ="SELECT p.virtuemart_product_id, p.product_type, p.product_state, p.product_cash_price, p.product_cash_comment AS comment,mf.mf_name, cb.vm_user_id "
                    ." FROM #__virtuemart_products AS p"
                    ." JOIN #__virtuemart_product_manufacturers AS m ON p.virtuemart_product_id = m.virtuemart_product_id"
                    ." JOIN #__virtuemart_manufacturers_fr_fr AS mf ON m.virtuemart_manufacturer_id = mf.virtuemart_manufacturer_id"
                    . " JOIN #__vm_cashbag AS cb ON p.cashbag_id = cb.id "
                    . " WHERE p.cashbag_id = $bag_id GROUP BY p.virtuemart_product_id";
            
            $db->setQuery($query);
            $resultat = $db->loadObjectList();
            //var_dump($query);die();
            if(count($resultat)>0){
                $total=0;$nb=0;
                $html = '<table width="650px"><tr><th width="75px">Type</th><th width="75px">Marque</th><th width="75px">Etat</th><th width="350px">Commentaire</th><th width="75px">Prix</th></tr>';//
                foreach ($resultat as $r){
                    $nb++;
                    $total += $r->product_cash_price;
                    //<td>".str_replace('_', ' ', $r->comment)."</td>
                    $html   .="<tr style='text-align:center;'><td> $r->product_type </td><td> $r->mf_name </td><td> ".str_replace('_', ' ', $r->product_state)." </td><td>$r->comment</td><td> $r->product_cash_price </td></tr>";
                }
                $html   .= '</table>';
                $html .= "<h2>Total $total Euros pour $nb articles</h2>";
            }  else {
                $html   = 'Aucun produit trouvé pour ce CASH BAG';
            }
            return $html;
        }
        
       public function editBag($id){
			
			$db		= &JFactory::getDbo();
            $id2	= JFactory::getApplication()->input->get('bag_id');
            $bag_id = ($id == -1)?$id2:$id;
            
            $query  ="SELECT p.virtuemart_product_id As id,  p.product_type, p.product_state, p.product_cash_price, p.product_cash_comment AS comment,mf.mf_name, cb.vm_user_id "
                    ." FROM #__virtuemart_products AS p"
                    ." JOIN #__virtuemart_product_manufacturers AS m ON p.virtuemart_product_id = m.virtuemart_product_id"
                    ." JOIN #__virtuemart_manufacturers_fr_fr AS mf ON m.virtuemart_manufacturer_id = mf.virtuemart_manufacturer_id"
                    . " JOIN #__vm_cashbag AS cb ON p.cashbag_id = cb.id "
                    . " WHERE p.cashbag_id = $bag_id GROUP BY p.virtuemart_product_id";
            
            $db->setQuery($query);
            $resultat = $db->loadObjectList();
            //var_dump($query);die();
            if(count($resultat)>0){
			$html	.= "<h1>Validation d'un CASHBAG (Cochez les produits que vous souhaitez supprimer) </h1><form action='index.php' method='post'>";
                $total=0;$nb=0;
                $html .= '<table width="650px"><tr><th>#</th><th width="75px">Type</th><th width="75px">Marque</th><th width="75px">Etat</th><th width="350px">Commentaire</th><th width="75px">Prix</th></tr>';//
                foreach ($resultat as $r){
                    $nb++;
                    $total += $r->product_cash_price;
                    //<td>".str_replace('_', ' ', $r->comment)."</td>
                    $html   .="<tr style='text-align:center;'><td><input type='checkbox' name='pid[]' id='$r->id' value='$r->id'/><td> $r->product_type </td><td> $r->mf_name </td><td> ".str_replace('_', ' ', $r->product_state)." </td><td>$r->comment</td><td> $r->product_cash_price </td></tr>";
                }
                $html   .= '</table>';
                $html 	.= "<h2>Total $total Euros pour $nb articles</h2>";
				$html	.= "<input type='hidden' name='option' value='com_cashbag'/>
							<input type='hidden' name='view' value='products'/>
							<input type='hidden' name='task' value='delete'/>
							<input type='hidden' name='layout' value='details'/>
							<input type='hidden' name='cashbag_id' value='$bag_id'/>";
				$html	.=	"<input type='submit' id='delete_prod' value='supprimer'/> ";
            }  else {
                $html   = '<h1>Aucun produit trouvé pour ce CASH BAG</h1>';
            }
            return $html;
	   }
       
	   function delete_prod(){
	   
	   
	   if(isset($_POST['pid'])){
	  // var_dump($_POST['pid']);die();
	   $db	= &JFactory::getDbo();
	   $res	= true;
			foreach($_POST['pid'] as $id){
			
			/*Delete produc*/
				$query	= "DELETE FROM #__virtuemart_products  WHERE virtuemart_product_id = $id";
				$db->setQuery($query);
				$res	= $res && $db->query();
				if(!$res){var_dump($res);die($query);}
			/*delete product price*/
				$query	= "DELETE FROM #__virtuemart_product_prices WHERE virtuemart_product_id = $id";
				$db->setQuery($query);
				$res	= $res && $db->query();
				if(!$res){var_dump($res);die($query);}
			/*delete product descr*/
				$query	= "DELETE FROM #__virtuemart_products_fr_fr WHERE virtuemart_product_id = $id";
				$db->setQuery($query);
				$res	= $res && $db->query();
				if(!$res){var_dump($res);die($query);}
				}
				
			/*mise à jour du nombre de produit*/
			$app	= &JFactory::getApplication()->input;
			
			$id    	= $app->get('cashbag_id');
			$db     = &JFactory::getDbo();
            $query  = "SELECT count(*) FROM #__virtuemart_products  WHERE cashbag_id = $id ";
            $db->setQuery($query);
            
            $nb     = $db->loadResult();
			
			$query	= "UPDATE #__vm_cashbag SET number_of_product_cash = $nb WHERE id = $id";
			$db		= &JFactory::getDbo();
			$db->setQuery($query);
            
            $res = $res && $db->query();
			
			if(!$res){var_dump($res);die($query);}
		}
		else{
		return '<h1>Vous n\'avez sélectionné aucun produit</h1>';
		}
		
		return CashbagModelProducts::editBag($id);
	   }
        //***************************************************************************************************************************
	protected function _buildQuery()
	{
		return parent::_buildQuery();
	}
	
	/**
	 * Method to store the Item
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	public function store($data)
	{
		$row =& $this->getTable();
		/**
		 * Example: get text from editor 
		 * $Text  = JRequest::getVar( 'text', '', 'post', 'string', JREQUEST_ALLOWRAW );
		 */
		 
		// Bind the form fields to the table
		if (!$row->bind($data)) {
			$this->setError($row->getError());
			return false;
		}

		// Make sure the table is valid
		if (!$row->check()) {
			$this->setError($row->getError());
			return false;
		}
		
		/**
		 * Clean text for xhtml transitional compliance
		 * $row->text		= str_replace( '<br>', '<br />', $Text );
		 */
	
		// Store the table to the database
		if (!$row->store()) {
			$this->setError($row->getError());
			return false;
		}
		$this->setId($row->{$row->getKeyName()});
		return $row->{$row->getKeyName()};
	}	

	/**
	* Method to build the Order Clause
	*
	* @access private
	* @return string orderby	
	*/
	
	protected function _buildContentOrderBy() 
	{
		$app = &JFactory::getApplication('');
		$context			= $this->option.'.'.strtolower($this->getName()).'.list.';
		$filter_order = $app ->getUserStateFromRequest($context . 'filter_order', 'filter_order', $this->getDefaultFilter(), 'cmd');
		$filter_order_Dir = $app ->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '', 'word');
		$this->_query->order($filter_order . ' ' . $filter_order_Dir );
	}
	
	/**
	* Method to build the Where Clause 
	*
	* @access private
	* @return string orderby	
	*/
	
	protected function _buildContentWhere() 
	{
		
		$app = &JFactory::getApplication('');
		$context			= $this->option.'.'.strtolower($this->getName()).'.list.';		
		$filter_state = $app ->getUserStateFromRequest($context . 'filter_state', 'filter_state', '', 'word');		
		$filter_order = $app ->getUserStateFromRequest($context . 'filter_order', 'filter_order', $this->getDefaultFilter(), 'cmd');
		$filter_order_Dir = $app ->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', 'desc', 'word');
		$search = $app ->getUserStateFromRequest($context . 'search', 'search', '', 'string');
					
		if ($search) {
			$this->_query->where('LOWER(a.product_params) LIKE ' . $this->_db->Quote('%' . $search . '%'));			
		}		
		if ($filter_state) {
			if ($filter_state == 'P') {
				$this->_query->where("a.published = 1");
			} elseif ($filter_state == 'U') {
					$this->_query->where("a.published = 0");
			} else {
				$this->_query->where("a.published > -2");
			}
		}		
	}
	
}
?>